import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '../stores/auth'

const isElectronProd = import.meta.env.MODE === 'production' && window.process?.versions?.electron

const service = axios.create({
    baseURL: isElectronProd
        ? 'http://39.100.95.39:6001'
        : import.meta.env.VITE_API_BASE_URL,
    timeout: 30000,
    headers: {
        'Content-Type': 'application/json'
    }
})

service.interceptors.request.use(
    config => {
        const authStore = useAuthStore()

        if (authStore.token && !config.url?.endsWith('/api/login')) {
            config.headers.Authorization = `Bearer ${authStore.token}`
        }

        return config
    },
    error => {
        console.error('请求拦截器错误:', error)
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        const res = response.data

        if (typeof res === 'string') {
            if (res.includes('认证失败') || res.includes('无法访问')) {
                const errMsg = res || '认证失败，无法访问系统资源'
                ElMessage.error(errMsg)
                return Promise.reject(new Error(errMsg))
            }
            return res
        } else if (typeof res === 'object') {
            if (res.code !== undefined && res.code !== 200 && res.code !== 0) {
                const errMsg = res.message || '操作失败'
                ElMessage.error(errMsg)
                return Promise.reject(new Error(errMsg))
            }

            if (res.message && (res.message.includes('认证失败') || res.message.includes('无法访问'))) {
                ElMessage.error(res.message)
                return Promise.reject(new Error(res.message))
            }

            return res
        }

        return res
    },
    error => {
        let errorMessage = '请求错误'

        if (error.response) {
            const serverMessage = error.response.data?.message ||
                error.response.data?.error ||
                error.response.statusText

            errorMessage = `请求失败: ${serverMessage || `HTTP ${error.response.status}`}`

            if (error.response.status === 401) {
                const authStore = useAuthStore()
                authStore.logout()
                if (!window.location.pathname.includes('/login')) {
                    window.location.href = '/login'
                }
            }
        } else if (error.request) {
            errorMessage = '网络错误，请检查网络连接'
        } else {
            errorMessage = error.message || '请求配置错误'
        }

        if (import.meta.env.DEV) {
            console.error('[请求错误]', {
                url: error.config?.url,
                method: error.config?.method,
                message: errorMessage,
                error: error
            })
        }

        if (!error.config?.url?.endsWith('/api/login')) {
            ElMessage.error(errorMessage)
        }

        return Promise.reject(error)
    }
)

export default service